import React from "react";
import styled from "styled-components";
import { useTags } from "hooks/useTags";

const Wrapper = styled.section`
  background: #ffffff;
  padding: 12px 16px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-end;
  >ol {
    margin: 0 -12px;
    > li {
      background: #d9d9d9;
      border-radius: 18px;
      display: inline-block;
      padding: 3px 18px;
      font-size: 14px;
      margin: 8px 12px;
      &.selected {
        background: #f60;
      }
    }
  }
  > button {
    background: none;
    border: none;
    padding: 2px 4px;
    border-bottom: 1px solid #333;
    color: #666;
    margin-top: 8px;
  }
`
type Props = {
  value: number[],
  onChange: (selected: number[])=> void
}
const TagsSection: React.FC<Props> = (props) => {
  const {tags, addTag} = useTags();
  const selectedTagIds = props.value; //被选中的标签id集合

  // 选中标签，并添加高亮
  const onToggleTag = (tagId: number)=> {
    const index = selectedTagIds.indexOf(tagId);
    if(index >= 0) {
      // 如果tag 已被选中，就复制多有没有被选中的tag，作为新的selectedTagIds
      props.onChange(selectedTagIds.filter(t=> t !== tagId));
    } else {
      props.onChange([...selectedTagIds, tagId])
    }
  };
  // 是否拥有高亮的class
  const getClass = (tagId: number)=> {
    return selectedTagIds.indexOf(tagId) >= 0? 'selected' : ''; 
  }
  return (
    <Wrapper>
      <ol>
        {tags.map(tag=> {
          return (
            <li key={tag.id} onClick={()=> {onToggleTag(tag.id)}} className={getClass(tag.id)}>{tag.name}</li>
          )
        })}
      </ol>
      <button onClick={addTag}>新增标签</button>
    </Wrapper>
  )
}

export { TagsSection }